﻿using System;

using MosCraft.Utilities;

namespace MosCraft.Terrain.WorldGen
{
    public class WorldGenTrees : WorldGenerator
    {
        public WorldGenTrees()
        {
        }

        override public bool generate(World world, FastRandom random, int x, int y, int z)
        {
            int l = random.nextInt(3) + 4;

            bool flag = true;

            if(y < 1 || y + l + 1 > 128)
            {
                return false;
            }

            for(int i1 = y; i1 <= y + 1 + l; i1++)
            {
                byte byte0 = 1;
                if(i1 == y)
                {
                    byte0 = 0;
                }
                if(i1 >= (y + 1 + l) - 2)
                {
                    byte0 = 2;
                }
                for(int i2 = x - byte0; i2 <= x + byte0 && flag; i2++)
                {
                    for(int l2 = z - byte0; l2 <= z + byte0 && flag; l2++)
                    {
                        if(i1 >= 0 && i1 < 128)
                        {
                            int j3 = world.getBlockID(i2, i1, l2);
                            if(j3 != 0 && j3 != Block.Leaves.blockID)
                            {
                                flag = false;
                            }
                        } else
                        {
                            flag = false;
                        }
                    }

                }

            }

            if(!flag)
            {
                return false;
            }

            int j1 = world.getBlockID(x, y - 1, z);
            if(j1 != Block.Grass.blockID && j1 != Block.Dirt.blockID || y >= 128 - l - 1)
            {
                return false;
            }

            world.setBlockID(x, y - 1, z, Block.Dirt.blockID);
            for(int k1 = (y - 3) + l; k1 <= y + l; k1++)
            {
                int j2 = k1 - (y + l);
                int i3 = 1 - j2 / 2;
                for(int k3 = x - i3; k3 <= x + i3; k3++)
                {
                    int l3 = k3 - x;
                    for(int i4 = z - i3; i4 <= z + i3; i4++)
                    {
                        int j4 = i4 - z;
                        if ((Math.Abs(l3) != i3 || Math.Abs(j4) != i3 || random.nextInt(2) != 0 && j2 != 0) && !Block.opaqueCubeLookup[world.getBlockID(k3, k1, i4)])
                        {
                            world.setBlockID(k3, k1, i4, Block.Leaves.blockID);
                        }
                    }

                }

            }

            for(int l1 = 0; l1 < l; l1++)
            {
                int k2 = world.getBlockID(x, y + l1, z);
                if(k2 == 0 || k2 == Block.Leaves.blockID)
                {
                    world.setBlockID(x, y + l1, z, Block.Wood.blockID);
                }
            }

            return true;
        }
    }
}
